package com.love.zywanandroid.retrofit

import com.love.zywanandroid.retrofit.api.HttpUrl
import com.zat.mes.andrmes.retrofit.NullOnEmptyConverterFactory
import com.zat.mes.andrmes.utils.PreferencesUtil
import okhttp3.*
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * @author zy
 * @date :2020-02-04 10:24
 * @description:
 */
class RetrofitManager private constructor() {


    companion object {
        val JOSNTYPE = MediaType.parse("application/json; charset=utf-8")
        private fun <T> getService(baseUrl: String, service: Class<T>): T {
            val client = OkHttpClient.Builder()
                .addInterceptor(getHeaderInterceptor())
                .addInterceptor(LoggingInterceptor())
                .connectTimeout(30L, TimeUnit.SECONDS)
                .readTimeout(30L, TimeUnit.SECONDS)
                .writeTimeout(30L, TimeUnit.SECONDS)
                .build();
            val retrofit = Retrofit.Builder()
                .baseUrl(HttpUrl.URL_BASE)
                .addConverterFactory(NullOnEmptyConverterFactory())
                .addConverterFactory(GsonConverterFactory.create())
                .client(client)
                .build();
            return retrofit.create(service)

        }

        fun <T> apiService(service: Class<T>): T {
            return getService(HttpUrl.URL_BASE, service)
        }

        /**
         * 统一添加头部信息
         */
        private fun getHeaderInterceptor(): Interceptor {
            val token = PreferencesUtil.getString(com.zat.mes.andrmes.global.CompanionType.TOKEN)
            val corpid = PreferencesUtil.getString(com.zat.mes.andrmes.global.CompanionType.CORPID)
            return object : Interceptor {
                override fun intercept(chain: Interceptor.Chain): Response {
                    val original = chain.request();

                    val requestBuilder: Request.Builder = original.newBuilder()
                        .header("plat", "Android")
                        .header("deviceId", PreferencesUtil.getString("deviceId"))
                    requestBuilder.header("token", token)
                    requestBuilder.header("corpid", corpid)
                    val request = requestBuilder.build()
                    return chain.proceed(request);
                }

            }
        }

    }


}
